from flask import Blueprint,jsonify,request

from utils.acl import acl

from comm import get_data

from utils.tokens import token1

from utils.redis_bp import Rediscon,r

from utils.db import db1





bp_login = Blueprint('login',__name__)



@bp_login.route('/mylogin',methods=["POST"])
def mylogin():

    data = get_data()

    sql = "select * from users where admin = '%s' and password = '%s'" % (str(data['username']),str(data['password']))

    res = db1.find(sql)

    if res:
        # 添加认证权限，
        pagelist = acl.get_page_reslist(res['id'])

        print(pagelist)

        interfacelist = acl.get_interface_reslist(res['id'])

        pagelist1 = pagelist + interfacelist

        print(pagelist1)

        key = 'interface' + str(res['id'])

        r.str_set(key,pagelist1)

        token = token1.encode_jwt(int(res['id']),60*60,"123")

        return jsonify({'code':200,'userid':res['id'],'token':token,'url1':pagelist1})
    else:
        return jsonify({'code':400,'mes':'ok'})








def get_courses(data):
    # 把顶级拿出来放在列表中
    list = []

    idlist = []
    for i in data:
        id = i['pid']
        if id == None:
            pass
        else:
            if id not in idlist:
                list.append({'id':id,'name':i['pname'],'son':[]})
                idlist.append(id)

    for j,value in enumerate(list):
        for i in data:
            if value['id'] == i['pid']:
                if value['id'] == None:
                    pass
                else:
                    list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
    return list

# res = [{'name': '组织用户', 'url': '/index', 'id': 1, 'pid': None, 'pname': None}, {'name': '组织管理', 'url': '/shu', 'id': 2, 'pid': 1, 'pname': '组织用户'}, {'name': '左', 'url': '/left', 'id': 3, 'pid': 1, 'pname': '组织用户'}, {'name': '用户管理', 'url': '/users', 'id': 4, 'pid': 1, 'pname': '组织用户'}, {'name': '职务管理', 'url': '/zhiwu', 'id': 5, 'pid': 1, 'pname': '组织用户'}, {'name': '岗位管理', 'url': '/props', 'id': 6, 'pid': 1, 'pname': '组织用户'}]
#
# print(get_courses(res))










@bp_login.route('/get_course')
def get_course():
    uid = request.args.get('uid')
    res = acl.get_recourse(uid)
    res1 = get_courses(res)
    return jsonify({'code':200,'list':res1})


